//登录与注册 仓库
import { reqGetCode, reqUserRegister, reqUserLogin, reqGetUserInfo, reqLogOut } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/token'
const state = {
    code: '',
    token: getToken(),
    userData: {}
}
const actions = {
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone)
        // console.log(phone);
        // console.log(result);
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async register({ commit }, userInfo) {
        let result = await reqUserRegister(userInfo)
        console.log(result);
        if (result.code == 200) {
            return 'ok'
        }
        else {
            Promise.reject(new Error('faile'))
        }
    },
    async login({ commit }, data) {
        let result = await reqUserLogin(data)
        // console.log(data);
        // console.log(result);
        if (result.code == 200) {
            commit('LOGIN', result.data.token)
            // console.log(result.data.token);
            // localStorage.setItem('TOKEN', result.data.token)
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async getUserInfo({ commit }) {
        let result = await reqGetUserInfo()
        // console.log(result);
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    async logout({ commit }) {
        let result = await reqLogOut()
        if (result.code == 200) {
            commit('LOGOUT')
            return 'ok'
        }
        else {
            return Promise.reject(new Error('faile'))
        }
    }

}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    LOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userData) {
        state.userData = userData
    },
    LOGOUT(state) {
        state.token = ''
        state.userData = {}
        removeToken()  //清空TOKEN本地存储
    }
}
const getters = {

}
export default {
    state,
    actions,
    mutations,
    getters
}